Ext.require([
    'Ext.window.*',
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.state.*'
]);

// Define Company entity
// Null out built in convert functions for performance *because the raw data is known to be valid*
// Specifying defaultValue as undefined will also save code. *As long as there will always be values in the data, or the app tolerates undefined field values*
// var row = null;
var win,form;
Ext.onReady(function() {
    // Ext.QuickTips.init();
    initForm();
    initWin()
    // sample static data for the store

    // var myData = [
    //     [1,'张三',23],
    //     [2,'李四',23],
    //     [3,'王五',23]
    // ];
    Ext.define('User', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'id',type: 'String'},
            {name: 'name',type: 'String'},
            {name: 'age',type: 'int'}
        ],
        idProperty: 'id'
    });
    /**
     * Custom function used for column renderer
     * @param {Object} val
     */

    // create the data store
    var store = Ext.create('Ext.data.Store', {
            model: 'User',
            proxy: {
                type: 'ajax',
                url: '/getUser.json',
                reader: {
                    type: 'json',
                    rootProperty: 'users'
                }
            },
            autoLoad: true
        });
    console.log(store)
    // create the Grid
    var grid = Ext.create('Ext.grid.Panel', {
        store: store,
        // url:'/getUser.json',
        collapsible: true,
        renderTo:Ext.getBody(),
        // multiSelect: true,
        forceFit: true,
        border: false,
        header: false,
        selModel : {
            selType : 'rowmodel',
            mode : 'SINGLE'
        },
        dockedItems: [{
            xtype: 'toolbar',
            dock: 'top',
            ui: 'footer',
            defaults: {minWidth: 40},
            items: [
                // { xtype: 'component', flex: 1 },
                { xtype: 'button', text: '新增',handler:function () {
                    add();
                }},
                { xtype: 'button', text: '修改',handler:function(){
                    var row = grid.getSelectionModel().getSelection();
                    console.log(row)
                    if(row.length != 0){
                        edit(row);
                    }else{
                        // alert("1")
                        Ext.MessageBox.alert('提示','选择一行')
                    }
                }},
                { xtype: 'button', text: '删除',handler:function(){
                    var row = grid.getSelectionModel().getSelection();
                    console.log(row)
                    if(row.length != 0){
                        deleteUser(row);
                    }else{
                        // alert("1")
                        Ext.MessageBox.alert('提示','选择一行')
                    }
                }}
            ]
        }],
        // listeners: {
        //     selectionchange : function(model, records) {
        //         if (records != 'undefined' && records.length > 0) {
        //             row = records[0].data;		//获取行数据
        //             console.log(row)
        //         }
        //     }
        // },
        columns: [
            {
                text     : '编号',
                width: 200,
                sortable : false,
                dataIndex: 'id'
            },
            {
                text     : '名字',
                width    : 75,
                sortable : true,
                dataIndex: 'name'
            },
            {
                text     : '年龄',
                width    : 75,
                sortable : true,
                dataIndex: 'age'
            }
        ],
        viewConfig: {
            stripeRows: true,
            enableTextSelection: true
        }

    });
    function add() {
        form.getForm().reset();
        win.setTitle("添加");
        win.show();
    }
    function edit(row) {
        console.log(row[0]);
        form.getForm().loadRecord(row[0]);
        win.setTitle("编辑");
        win.show();
    }
    function deleteUser(row) {
        Ext.Ajax.request({
            url: 'deleteUser.json',
            params: {
                id: row[0].data.id
            },
            success: function(response){
                grid.getStore().reload();
                console.log(response)
                Ext.Msg.alert('Success', response.responseText);
            }
        });
    }
    function initWin() {
        win = Ext.create("Ext.window.Window", {
            title: "编辑",       //标题
            draggable: false,
            closeAction:'hide',
            height: 300,                          //高度
            width: 400,                           //宽度
            layout: "fit",                        //窗口布局类型
            modal: true, //是否模态窗口，默认为false
            resizable: false,
            items: [form]
        });
    }

    function initForm() {
        form = Ext.create('Ext.form.Panel', {
            id: 'formId',
            url: 'saveUser.json',
            // columnWidth : '50%',
            width:400,
            layout:'form',
            items: [{
                layout : "column",
                columnWidth : .6,
                padding:'30 0 0 100',
                items:[{
                    xtype: 'textfield',
                    fieldLabel: '编号',
                    name: 'id',
                    id:'id',
                    hidden:true,
                    labelWidth:30,
                }]
            },{
                layout : "column",
                columnWidth : .5,
                padding:'30 0 0 100',
                items:[{
                    layout : "column",
                    xtype: 'textfield',
                    fieldLabel: '名字',
                    name: 'name',
                    id:'name',
                    columnWidth : .6,
                    labelWidth:30,
                }]
            },{
                layout : "column",
                columnWidth : .5,
                padding:'30 0 0 100',
                items:[{
                    layout : "column",
                    xtype: 'numberfield',
                    fieldLabel: '年龄',
                    name: 'age',
                    id:'age',
                    minValue:0,
                    columnWidth : .6,
                    labelWidth:30,
                }]
            }],
            buttons: [{
                text: '提交',
                handler: function() {
                    // The getForm() method returns the Ext.form.Basic instance:
                    var form = this.up('form').getForm();
                    console.log(form)
                    if (form.isValid()) {
                        // Submit the Ajax request and handle the response
                        form.submit({
                            success: function(form, action) {
                                // console.log(action)
                                win.close();
                                grid.getStore().reload();
                                Ext.Msg.alert('Success', action.result.success);
                            },
                            failure: function(form, action) {
                                Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
                            }
                        });
                    }
                }
            }]
        });
    }

});




